﻿
using System.Security.Cryptography;

namespace CoreWeb.Utility.Middleware
{
    public class RefuseStealingMiddleWare
    {
        private readonly RequestDelegate _next;
        public RefuseStealingMiddleWare(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext content)
        {
            string url = content.Request.Path.Value;
            string urlReferrer = content.Request.Headers["Referer"]; //当前请求的域名
            if (!url.Contains(".jpg"))
            {
                await _next(content); //不在处理
            }
            else if (string.IsNullOrWhiteSpace(urlReferrer)) //如果为空
            {
                await SetForbiddenImage(content);//返回拒绝图片
            }
            else if (!urlReferrer.Contains("localhost"))//如果不包含本服务器域名
            {
                await SetForbiddenImage(content);//返回拒绝图片
            }
            else
            {
                await _next(content);//不在处理
            }
        }

        private async Task SetForbiddenImage(HttpContext content)
        {
            string defaultImagePath = "wwwroot/Images/Forbidden.jpg";
            string path = Path.Combine(Directory.GetCurrentDirectory(), defaultImagePath);
            FileStream fs=File.OpenRead(path);
            byte[] buffer = new byte[fs.Length];
            await fs.ReadAsync(buffer, 0, buffer.Length);
            await content.Response.Body.WriteAsync(buffer,0, buffer.Length);
        }
    }
}
